package com.example.guetdemo.handler;

import com.example.guetdemo.enums.AppHttpCodeEnum;
import com.example.guetdemo.result.ResponseResult;
import com.example.guetdemo.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseResult exceptionHandler(Exception e) {
        log.error("出现异常了！",e);
        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
    }

    /**
     * 参数校验全局异常处理
     */
    @ExceptionHandler(BindException.class)
    public ResponseResult bindExceptionHandler(ServletRequest servletRequest, ServletResponse servletResponse,BindException e) {
        log.error("出现了异常",e);
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        WebUtils.setStatus(response,422);
        return ResponseResult.errorResult(422, String.valueOf(e.getBindingResult().getAllErrors().get(0)));
    }
}
